#!/bin/sh
# Copyright (C) 2023 jjm2473@gmail.com

[ -f /lib/netifd/mac80211.sh ] || exit 0

. /lib/netifd/mac80211.sh

lookup_phy() {
    local device="$1"
    local devpath
    config_get devpath "$device" path
    [ -n "$devpath" ] && {
        phy="$(mac80211_path_to_phy "$devpath")"
        [ -n "$phy" ] && return
    }

    local macaddr="$(config_get "$device" macaddr | tr 'A-Z' 'a-z')"
    [ -n "$macaddr" ] && {
        for _phy in /sys/class/ieee80211/*; do
            [ -e "$_phy" ] || continue

            [ "$macaddr" = "$(cat ${_phy}/macaddress)" ] || continue
            phy="${_phy##*/}"
            return
        done
    }
    phy=
    return
}

delete_ap_of()
{
    local device
    config_get device "$1" "device"
    [[ "$device" = "$2" ]] || return 0
    local mode
    config_get mode "$1" "mode"
    [[ "$mode" = "ap" ]] || return 0

    uci_remove "wireless" "$1"
}

patch_if_iwlwifi()
{
    local type
    local path
    local module

    config_get type "$1" "type"
    [[ "$type" = "mac80211" ]] || return 0
    phy=
    lookup_phy "$1"
    [ -z "$phy" ] && return 0
    [ -h "/sys/class/ieee80211/$phy/device/driver" ] || return 0

    path="$(readlink "/sys/class/ieee80211/$phy/device/driver")"
    module="${path##*/}"
    [[ "$module" = "iwlwifi" ]] || return 0

    config_foreach delete_ap_of wifi-iface "$1"
}

patch_all_config()
{
    . /lib/functions.sh
    config_load "wireless"
    config_foreach patch_if_iwlwifi wifi-device
    uci_commit "wireless"
}

if [ -f /etc/config/wireless ]; then
    sleep 1
    patch_all_config
fi

exit 0
